package initialition

import (
	"fmt"
	"github.com/elastic/go-elasticsearch/v7"
	"github.com/nacos-group/nacos-sdk-go/clients"
	"github.com/nacos-group/nacos-sdk-go/common/constant"
	"github.com/nacos-group/nacos-sdk-go/vo"
	"github.com/spf13/viper"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"lb_two-exam/doctor-srv/global"
	"lb_two-exam/doctor-srv/internal/model/dao"
	"os"
)

func init() {
	InitConfig()
	InitNacos()
	InitDB()
	//InitEs()
}
func InitConfig() {
	viper.SetConfigFile("./config/dev.yaml")

	err := viper.ReadInConfig()
	if err != nil {
		panic(err)
	}
	viper.Unmarshal(&global.GlobalNacos)
	viper.Unmarshal(&global.GlobalConfig)
	fmt.Println(global.GlobalNacos)
	fmt.Println(global.GlobalConfig)
}
func InitNacos() {

	os.MkdirAll("./tmp/nacos/log", 0777)
	os.MkdirAll("./tmp/nacos/cache", 0777)
	//create clientConfig
	clientConfig := constant.ClientConfig{
		NamespaceId:         global.GlobalNacos.Nacos.NameSpace,
		TimeoutMs:           5000,
		NotLoadCacheAtStart: true,
		LogDir:              "./tmp/nacos/log",
		CacheDir:            "./tmp/nacos/cache",
		LogLevel:            "debug",
		Username:            global.GlobalNacos.Nacos.Username,
		Password:            global.GlobalNacos.Nacos.Password,
	}
	// At least one ServerConfig
	serverConfigs := []constant.ServerConfig{
		{
			IpAddr:      global.GlobalNacos.Nacos.Addr,
			ContextPath: "/nacos",
			Port:        global.GlobalNacos.Nacos.Port,
			Scheme:      "http",
		},
	}
	// Another way of create config client for dynamic configuration (recommend)
	configClient, err := clients.NewConfigClient(
		vo.NacosClientParam{
			ClientConfig:  &clientConfig,
			ServerConfigs: serverConfigs,
		},
	)
	if err != nil {
		panic(err)
	}
	_, err = configClient.GetConfig(vo.ConfigParam{
		DataId: global.GlobalNacos.Nacos.DataId,
		Group:  global.GlobalNacos.Nacos.Group})
	//fmt.Println(content)

}

func InitDB() {
	var err error
	config := global.GlobalConfig.Mysql
	dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8&parseTime=True", config.User, config.Password, config.Host, config.Port, config.Database)
	global.DB, err = gorm.Open(mysql.Open(dsn))
	if err != nil {
		panic(err)
	}
	fmt.Println("MySQL connect successful!!")
	global.DB.AutoMigrate(&dao.Doctor{}, &dao.Person{}, &dao.Message{})
}

func InitEs() {
	cfg := elasticsearch.Config{
		Addresses: []string{
			"http://117.27.231.169:9200",
		},
		// ...
	}
	es, err := elasticsearch.NewClient(cfg)
	if err != nil {
		panic(err)
	}
	fmt.Println(es)

}
